package com.zerocarbon.framework.common.dto;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zerocarbon.framework.common.model.BaseEntity;
import com.zerocarbon.framework.common.utils.AntiSqlFilter;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分页参数
 * @author wyf
 * 2020年7月10日
 */
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
public abstract class PageParamDTO extends BaseDTO implements Serializable {
	
	private static final long serialVersionUID = 5605891666615355713L;
	
    private Long pageSize;

    private Long pageNo;

    private String sort;

    private String order;

    private Map<String, String> map = new HashMap<>(1);

    @JSONField(serialize = false)
    @JsonIgnore
    public IPage getPage() {
    	//PageParamDTO params = this;
    	long pageSize = this.getPageSize()==null?10l:this.getPageSize();
    	long pageNo = this.getPageNo()==null?1l:this.getPageNo();
    	String pageSort = this.getSort()==null? BaseEntity.CREATE_TIME: this.getSort();
    	String order = this.getOrder()==null?"descending":this.getOrder();
    	
        if (StrUtil.isEmpty(pageSort)) {
            Page page = new Page(pageNo, pageSize);
            return page;
        }

        Page page = new Page(pageNo, pageSize);
        List<OrderItem> orders = new ArrayList<>();
        // 简单的 驼峰 转 下划线
        String sort = StrUtil.toUnderlineCase(pageSort);

        // 除了 create_time 和 updateTime 都过滤sql关键字
        if (!StrUtil.equalsAny(pageSort, BaseEntity.CREATE_TIME, BaseEntity.UPDATE_TIME)) {
            sort = AntiSqlFilter.getSafeValue(sort);
        }
        
        orders.add("ascending".equals(order) ? OrderItem.asc(sort) : OrderItem.desc(sort));
        page.setOrders(orders);
        return page;

    }
}
